﻿using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.AssistClass;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.Common.Verification;
using Com.JunCaiSoft.Freeze.Dto;
using Com.JunCaiSoft.Freeze.Entity;
using Com.JunCaiSoft.Freeze.IDao;
using Com.JunCaiSoft.Freeze.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.Freeze.Controllers
{
    /// <summary>
    /// 借条管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class CreditContractController : BaseController<CreditContractView, CreditContractItem, CreditContract, Guid>
    {
        /// <summary>
        /// 配置
        /// </summary>
        private IConfiguration Configuration { get; set; }
        /// <summary>
        /// 配置环境
        /// </summary>
        private readonly IWebHostEnvironment HostingEnvironment;
        public CreditContractController(ICreditContractDao creditContractDao, IWebHostEnvironment env) : base(creditContractDao)
        {
            var builder = new ConfigurationBuilder()
                               .SetBasePath(env.ContentRootPath)
                               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                               .AddJsonFile("DataBaseExcute.json", optional: true, reloadOnChange: true);
            HostingEnvironment = env;
            Configuration = builder.Build();
        }
        /// <summary>
        /// 按借条ID单个删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public override async Task<ActionResult> DeleteSingleAsync(Guid Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();
                int result = await DaoAsync.DeleteListAsync<CreditContract>(x => x.Id == Id);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 按借条ID批量删除
        /// </summary>
        /// <param name="DeleteList"></param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> DeleteList)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = await DaoAsync.DeleteListAsync<CreditContract>(x => DeleteList.Contains(x.Id));

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize"></param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize, String keyword)
        {
            try
            {
                var columns = @" c.Id,
	                             c.Num,
	                             c.NumCode,
	                             c.Creditor,
	                             c.CreditorID,
	                             c.Amount,
	                             c.RatePeriod,
	                             c.Rate,
	                             c.LiquidatedDamages,
	                             c.SignDate,
	                             c.CreditContractFile,
	                             c.CreateTime  ";

                var tables = @" CreditContract c ";

                var where = @" 1 = 1 ";

                List<SqlParameter> bankParams = new List<SqlParameter>() { };

                if (keyword != "" && keyword != null)
                {

                    Regex rex = new Regex(@"(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)");

                    if (keyword.Length == 4 && rex.IsMatch(keyword))
                    {
                        where += " AND c.CreditorID like @CreditorOrCreditorID ";

                        SqlParameter QueryBankName = new SqlParameter("@CreditorOrCreditorID", "%" + keyword);

                        bankParams.Add(QueryBankName);
                    }
                    else
                    {
                        where += " AND c.Creditor like @CreditorOrCreditorID OR c.CreditorID like @CreditorOrCreditorID ";

                        SqlParameter QueryBankName = new SqlParameter("@CreditorOrCreditorID", "%" + keyword + "%");

                        bankParams.Add(QueryBankName);
                    }

                }

                var tmpResultList = await DaoAsync.QuerySQLByPageQuickAsync<CreditContractItemDto>(pageIndex, pageSize, " c.CreateTime desc ", columns, tables, where, bankParams.Select(x => ((ICloneable)x).Clone()).ToArray());

                var resultList = new QueryData<CreditContractItem>();

                var itemList = new List<CreditContractItem>();

                resultList.totalCount = tmpResultList.totalCount;

                tmpResultList.items.ToList().ForEach(item => itemList.Add(item.MapTo<CreditContractItem>()));

                resultList.items = itemList;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(resultList)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 创建借条信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<ActionResult> CreateAsync(CreditContractView entity)
        {
            try
            {
                DaoAsync.dbContext.Database.BeginTransaction();

                var saveone = entity.MapTo<CreditContract>();
                var result = await DaoAsync.InsertAsync(saveone);

                DaoAsync.dbContext.Database.CommitTransaction();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        /// <summary>
        /// 更新借条信息
        /// </summary>
        /// <param name="entityModel"></param>
        /// <returns></returns>
        [HttpPut]
        public override async Task<ActionResult> UpdateAsync(UpdateEntity<CreditContractView> entityModel)
        {
            DaoAsync.dbContext.Database.BeginTransaction();

            var saveone = entityModel.entity.MapTo<CreditContract>();
            var result = await DaoAsync.UpdateAsync(saveone, entityModel.Id);

            DaoAsync.dbContext.Database.CommitTransaction();
            return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
        }
        /// <summary>
        /// 身份证校验
        /// </summary>
        /// <param name="IDNumberStr"></param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> CheckIDNumber(String IDNumberStr)
        {
            try
            {
                var result = IDnumber.CheckIDnumber(IDNumberStr);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                return await Task.Run(() => Content(JsonConvert.SerializeObject(e.Message)));
            }
        }
        /// <summary>
        /// 创建借条
        /// </summary>
        /// <param name="ProjectManager"></param>
        /// <param name="ProjectManagerID"></param>
        /// <param name="Amount"></param>
        /// <param name="BigAmount"></param>
        /// <param name="FreezeRate"></param>
        /// <param name="FreezeRateType"></param>
        /// <param name="FreezeTime"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public virtual FileResult CreateWordContract(String ProjectManager, String ProjectManagerID, Double Amount, String BigAmount, Double FreezeRate, String FreezeRateType, DateTime FreezeTime)
        {
            try
            {

                switch (FreezeRateType)
                {
                    case "DAY":
                        FreezeRateType = "日";
                        break;
                    case "MONTH":
                        FreezeRateType = "月";
                        break;
                    case "YEAR":
                        FreezeRateType = "年";
                        break;
                    default:
                        FreezeRateType = "{{利率未定义}}";
                        break;
                }

                var contract = new CreditContractInfo
                {
                    ProjectManager = ProjectManager,
                    ProjectManagerID = ProjectManagerID,
                    Amount = Amount,
                    BigAmount = BigAmount,
                    FreezeRate = FreezeRate,
                    FreezeRateType = FreezeRateType,
                    Year = FreezeTime.Year.ToString(),
                    Month = FreezeTime.Month.ToString(),
                    Day = FreezeTime.Day.ToString()
                };

                var baseurl = Configuration.GetSection("APICores:BaseURL");

                String contentRootPath = HostingEnvironment.ContentRootPath;

                string physicalWebRootPath = contentRootPath + @"\ExportTemplate\CreditContract.docx";

                var file = WordNPOI.ExportObjet(physicalWebRootPath, contract);

                return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", contract.ProjectManager + "(" + contract.ProjectManagerID + ")借条" + ".docx");

            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<ActionResult> UploadImportFile(IFormFile file)
        {
            try
            {
                if (file == null)
                {
                    return BadRequest();
                }

                var filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName; // 原文件名（包括路径）

                var extName = filename.Substring(filename.LastIndexOf('.')).Replace("\"", "");// 扩展名

                var freeze_time = new DateTime(1970, 01, 01).AddMilliseconds(Double.Parse(Request.Form["FreezeTime"].ToString()));

                var project_manager = Request.Form["ProjectManager"].ToString();

                var project_manager_id = Request.Form["ProjectManagerID"].ToString();

                var count = (await DaoAsync.ListAsync(x => x.CreditorID == project_manager_id)).Count;

                int i = 1;

                var hostname = Configuration.GetSection("NASCore:Hostname");

                var username = Configuration.GetSection("NASCore:Username");

                var password = Configuration.GetSection("NASCore:Password");

                FtpHelper ftp = new FtpHelper(hostname.Value, username.Value, password.Value);

                ftp.RemotePath = "/home/Drive/";

                var FreezeFileName = freeze_time.ToString("yyyyMMdd") + "-JT(" + project_manager_id + ")-";

                string fileSavePath = Directory.GetCurrentDirectory() + @"/AttachFile/";//文件临时目录，导入完成后 删除

                if (!Directory.Exists(fileSavePath))
                {
                    Directory.CreateDirectory(fileSavePath);
                }

                while (ftp.Download(FreezeFileName + i.ToString() + extName, fileSavePath + FreezeFileName + i.ToString() + extName) && (i < count + 1))
                {
                    i++;
                }

                filename = fileSavePath + FreezeFileName + i.ToString() + extName; // 新文件名（包括路径）

                using (FileStream fs = System.IO.File.Create(filename)) // 创建新文件
                {
                    file.CopyTo(fs);// 复制文件

                    fs.Flush();// 清空缓冲区数据

                    //根据 filename 【文件服务器磁盘路径】可对文件进行业务操作
                }

                FileInfo fileInfo = new FileInfo(filename);

                string strCN = freeze_time.ToString("yyyyMMdd") + "-JT(" + project_manager_id + ")-" + i.ToString() + extName;

                ftp.Upload(fileInfo, strCN);


                return await Task.Run(() => Content(JsonConvert.SerializeObject("")));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        [HttpDelete]
        public virtual async Task<ActionResult> DeleteUploadFile(String UploadFile)
        {
            try
            {
                string fileSavePath = Directory.GetCurrentDirectory() + @"\Upload\";//文件临时目录，导入完成后 删除

                string filename = fileSavePath + UploadFile;

                //处理完成后，删除上传的文件
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }

                return await Task.Run(() => Content(JsonConvert.SerializeObject(true)));
            }
            catch (Exception e)
            {
                return await Task.Run(() => Content(JsonConvert.SerializeObject(false)));
            }

        }
    }
}
